Skip to content

Add kernel bundle states, kernel ids and SYCL library loading - #2440

Open
ndgrigorian wants to merge 11 commits into
masterfrom
feature/kernel-bundle-api
Open

ndgrigorian wants to merge 11 commits into
masterfrom
feature/kernel-bundle-api

Conversation

@ndgrigorian

@ndgrigorian ndgrigorian commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

This PR proposes expanding dpctl.compiler to include kernel bundles in the input, object and executable states, get_kernel_bundle and has_kernel_bundle, compile, link, build and join, the SyclKernelId and SyclDeviceImage classes, get_kernel_ids, is_compatible, and new SyclKernelBundle queries (state, backend, sycl_context, get_devices, is_empty, get_kernel_ids, has_kernel, get_kernel, get_device_images, specialization constant queries)

It also adds dpctl.compiler.load_kernel_library, which loads a shared library with SYCL device code, e.g. compiled for CUDA or HIP devices, and returns the ids of its kernels for use with get_kernel_bundle, and dpctl4pybind11.hpp type casters for sycl::kernel_bundle<sycl::bundle_state::input>, sycl::kernel_bundle<sycl::bundle_state::object> and sycl::kernel_id, with a new examples/pybind11/use_kernel_bundle example that sets a SYCL specialization constant on a kernel bundle obtained in Python

This includes a breaking change for dpctl.compiler.SyclKernel: the device-specific queries become methods taking an optional device, which defaults to the first device of the kernel bundle, and the matching DPCTLKernel_Get* C-API functions take a nullable DPCTLSyclDeviceRef. These queries now return 0 instead of terminating the process when the SYCL runtime throws

The PR also fixes a number of bugs in the existing kernel bundle C API:

  • DPCTLKernelBundle_GetKernel, DPCTLKernelBundle_HasKernel and DPCTLKernelBundle_CreateFromOCLSource let SYCL exceptions escape an extern "C" function, terminating the process
  • the OpenCL context, program and kernel references obtained through get_native and make_kernel_bundle/make_kernel were leaked
  • the Level Zero module and kernels were created with ownership::keep and never destroyed
  • the OpenCL and Level Zero build logs are now included in the error reported when compilation fails
  • DynamicLibHelper no longer closes a NULL handle when a library fails to open
  • create_kernel_bundle_from_spirv rejects non-contiguous buffers which were passed to the C API as contiguous
  • Have you provided a meaningful PR description?
  • Have you added a test, reproducer or referred to an issue with a reproducer?
  • Have you tested your changes locally for CPU and GPU devices?
  • Have you made sure that new changes do not introduce compiler warnings?
  • Have you checked performance impact of proposed changes?
  • Have you added documentation for your changes, if necessary?
  • Have you added your changes to the changelog?
  • If this PR is a work in progress, are you opening the PR as a draft?

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

@ndgrigorian
ndgrigorian force-pushed the feature/kernel-bundle-api branch from a3f6789 to 78a7927 Compare December 3, 2026 19:49
Comment on lines +57 to +59
if (DRef)
return static_cast<RetT>(
sycl_kern->get_info<Param>(*unwrap<device>(DRef)));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: A device that is not one of the kernel bundle's devices goes straight to get_info, and DPC++ does not check it. A Level Zero kernel asked about the OpenCL CPU crashes the process; other foreign devices give that device's numbers or 0:

import dpctl, dpctl.compiler as dpc

q = dpctl.SyclQueue("level_zero:gpu")
kb = dpc.get_kernel_bundle(q)
krn = kb.get_kernel(kb.get_kernel_ids()[0])
print(krn.work_group_size(dpctl.SyclDevice("opencl:cpu")))  # SIGSEGV, 5/5 on Lunar Lake

Could the device be checked against the bundle's devices, with a ValueError in Python for a foreign one?

Comment thread dpctl/compiler/_compiler.pxd Outdated
Comment on lines +75 to +77
cdef DPCTLSyclInputKernelBundleRef _input_ref
cdef DPCTLSyclObjectKernelBundleRef _object_ref
cdef int _state

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new fields grow SyclKernelBundle from 40 to 64 bytes. Every Cython or pybind11 module built against an earlier dpctl checks that size on import, so dpnp built without this PR warns, and with -W error it does not import:

RuntimeWarning: dpctl.compiler._compiler.SyclKernelBundle size changed, may indicate binary incompatibility. Expected 40 from C header, got 64 from PyObject

Those modules also get NULL from SyclKernelBundle_GetKernelBundleRef for an input or object bundle, and do not check it. Could input and object bundles be separate classes, so SyclKernelBundle keeps its layout?

Comment thread dpctl/compiler/_compiler.pyx Outdated
def work_group_size(self):
""" Returns the maximum number of work-items in a work-group that can
be used to execute the kernel on device it was built for.
def work_group_size(self, SyclDevice device=None):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This turns the properties into methods with no deprecation, and old code breaks silently: krn.work_group_size is now a bound method, so min(krn.work_group_size, 256) raises TypeError, and if krn.compile_sub_group_size: is always true. The C functions keep their names but take one more argument, so a binary built against an earlier dpctl passes garbage as DRef. Could the properties stay, deprecated, with the device queries under new names?

Comment on lines +440 to +447
#ifdef _WIN32
// the search flags require an absolute path, ERROR_INVALID_PARAMETER
// otherwise
void *Handle = LoadLibraryExA(Path, nullptr,
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS |
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
if (!Handle && GetLastError() == ERROR_INVALID_PARAMETER)
Handle = LoadLibraryExA(Path, nullptr, 0);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Windows this fails for three valid paths (error 126): a non-ASCII path like ...\папка_ядер\x.dll, since os.fsencode gives UTF-8 and LoadLibraryExA reads it in the ANSI code page; an absolute path with /; and a relative path to a DLL whose dependencies sit next to it, since the retry with flags 0 skips the DLL's folder. UTF-8 to UTF-16, GetFullPathNameW, then LoadLibraryExW with the same flags fixed all of them locally. The tests skip on Windows, so CI misses this.

Comment thread dpctl/compiler/_compiler.pyx Outdated
Comment on lines +2036 to +2039
return SyclKernelBundle._create(
ExeRef,
any((<SyclKernelBundle>b)._is_sycl_source for b in kernel_bundles),
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two joined SPIR-V bundles on Level Zero report the kernel but cannot create it. A join of a SYCL-source and a SPIR-V bundle does not find the SPIR-V kernels on any device:

import os, dpctl, dpctl.compiler as dpc

q = dpctl.SyclQueue("level_zero:gpu")
spv = open(os.path.join(os.path.dirname(dpctl.__file__), "tests/input_files/multi_kernel.spv"), "rb").read()
j = dpc.join([dpc.create_kernel_bundle_from_spirv(q, spv), dpc.create_kernel_bundle_from_spirv(q, spv)])
print(j.has_sycl_kernel("add"))  # True
j.get_sycl_kernel("add")  # ValueError on Level Zero; works on OpenCL GPU and CPU

The test joins a bundle with itself, which keeps one image. Could join refuse what get_sycl_kernel cannot handle?

Comment on lines +324 to +330
std::string msg =
"clBuildProgram failed: " + _GetErrorCode_ocl_impl(build_status);
const std::string &log = _GetBuildLog_ocl_impl(clProgram, clDevice);
if (!log.empty()) {
msg += "\nBuild log:\n" + log;
}
error_handler(msg, __FILE__, __func__, __LINE__, error_level::error);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The build log goes only to error_handler, which prints nothing unless DPCTL_VERBOSITY is set, so by default the error still has no message:

import dpctl, dpctl.compiler as dpc

q = dpctl.SyclQueue("opencl")
try:
    dpc.create_kernel_bundle_from_source(q, "kernel void add(global int* a) { a[0] = b; }")
except dpc.SyclKernelBundleCompilationError as e:
    print(repr(str(e)))  # ''

Could the log go into the exception, as DPCTLKernelBuildLog does for SYCL source?

Comment on lines +548 to +563
auto Before = sycl::get_kernel_ids();
std::string Error;
void *Handle = open_library(Path, Error);
if (!Handle) {
error_handler("Could not load " + std::string(Path) + ": " + Error,
__FILE__, __func__, __LINE__);
return nullptr;
}
auto It = Libs.KernelIds.find(Handle);
if (It == Libs.KernelIds.end()) {
std::unordered_set<kernel_id> Known(Before.begin(), Before.end());
std::vector<kernel_id> New;
for (const auto &KId : sycl::get_kernel_ids()) {
if (Known.count(KId) == 0)
New.push_back(KId);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ids are the difference of get_kernel_ids() before and after dlopen, so they include the kernels of every SYCL library loaded with this one, and that library then gets none:

import pathlib, subprocess, tempfile
import dpctl.compiler as dpc

src = """#include <sycl/sycl.hpp>
extern "C" SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((sycl::ext::oneapi::experimental::nd_range_kernel<1>))
void NAME(int *a) { a[sycl::ext::oneapi::this_work_item::get_nd_item<1>().get_global_id(0)] = 1; }
"""
d = pathlib.Path(tempfile.mkdtemp())
for name, libs in [("kb", []), ("ka", [f"-L{d}", "-lkb", f"-Wl,-rpath,{d}"])]:
    (d / f"{name}.cpp").write_text(src.replace("NAME", name))
    subprocess.run(["icpx", "-fsycl", "-fPIC", "-shared", d / f"{name}.cpp", "-o", d / f"lib{name}.so", *libs], check=True)

print([k.name for k in dpc.load_kernel_library(d / "libka.so")])  # ['__sycl_kernel_ka', '__sycl_kernel_kb']
print([k.name for k in dpc.load_kernel_library(d / "libkb.so")])  # []

For a library linked with oneMKL, get_kernel_bundle(q, kernel_ids=...) would then build oneMKL's kernels too. Could the docstring say this?

Comment thread dpctl/compiler/_compiler.pxd Outdated
Comment on lines 83 to 96
@staticmethod
cdef SyclKernelBundle _create_input (DPCTLSyclInputKernelBundleRef kbref)

@staticmethod
cdef SyclKernelBundle _create_object (DPCTLSyclObjectKernelBundleRef kbref)

cdef DPCTLSyclKernelBundleRef get_kernel_bundle_ref (self)
cdef DPCTLSyclInputKernelBundleRef get_input_kernel_bundle_ref (self)
cdef DPCTLSyclObjectKernelBundleRef get_object_kernel_bundle_ref (self)
cdef _require_executable (self, str what)
cdef bint _device_image_has_kernel (
self, size_t index, SyclKernelId kernel_id, SyclDevice device
)
cpdef SyclKernel get_sycl_kernel(self, str kernel_name)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These methods are declared before get_kernel_bundle_ref and get_sycl_kernel, so their vtable slots move from 1 and 2 to 3 and 8. A Cython module built against an earlier dpctl that calls kb.get_sycl_kernel(name) would call _create_object instead. Could the new methods go after get_sycl_kernel?

Comment thread dpctl/compiler/_compiler.pyx Outdated
Comment on lines +1025 to +1032
cdef api DPCTLSyclInputKernelBundleRef SyclKernelBundle_GetInputKernelBundleRef(
SyclKernelBundle kb
):
""" C-API function to access the opaque reference of a
:class:`dpctl.compiler.SyclKernelBundle` in ``input`` state, NULL for
other states.
"""
return kb.get_input_kernel_bundle_ref()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new C-API functions (SyclKernelBundle_GetInputKernelBundleRef, _GetObjectKernelBundleRef, _MakeInput, _MakeObject, SyclKernelId_GetKernelIdRef, SyclKernelId_Make) and PySyclKernelIdType are not in dpctl_capi.rst, which also still says SyclKernelBundle_GetKernelBundleRef always returns a bundle. 14 of the new libsyclinterface functions have no gtest, e.g. DPCTLInputKernelBundle_GetDevices and DPCTLObjectKernelBundle_GetKernelIds.

Comment on lines +28 to +44

#include "dpctl_sycl_kernel_bundle_interface.h"

#include "Config/dpctl_config.h"
#include "dpctl_error_handlers.h"
#include "dpctl_string_utils.hpp"
#include "dpctl_sycl_type_casters.hpp"
#include "dpctl_utils_helper.h"
#include <cstddef>
#include <functional>
#include <iterator>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <sycl/sycl.hpp>
#include <unordered_map>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#2384 guards the kernel bundle code with __ADAPTIVECPP__ (11 places in dpctl_sycl_kernel_bundle_interface.cpp), but this new file has none, and it uses kernel_id, compile, link and device image selectors. Whichever of the two PRs is merged second will need stubs here for the AdaptiveCpp build. Which order do you plan?

Comment thread dpctl/compiler/_compiler.pyx Outdated
if KIdRefs is NULL:
raise MemoryError()
for i in range(<size_t>len(kernel_ids)):
KIdRefs[i] = (<SyclKernelId>kernel_ids[i]).get_kernel_id_ref()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: SyclKernelId has no __cinit__, so SyclKernelId.__new__ gives an object with a NULL ref, and DPCTLKernelIdVector_CreateFromArray dereferences it:

import dpctl, dpctl.compiler as dpc

kid = dpc.SyclKernelId.__new__(dpc.SyclKernelId)
dpc.is_compatible([kid], dpctl.SyclDevice())  # SIGSEGV

Could _kernel_id_vector reject a NULL ref?

extern "C" SYCL_EXTERNAL
SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((syclext::nd_range_kernel<1>))
void bundle_state_test_kernel(int *a) {
a[syclext::this_work_item::get_nd_item<1>().get_global_id(0)] = 1;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This source does not compile with DPC++ 2026.2.1: get_nd_item is in sycl::ext::oneapi::this_work_item, not in experimental. It is not reached here because dpctl's own kernels give ids, so it would fail only where there are none. sycl::ext::oneapi::this_work_item::get_nd_item<1>(), as in test_sycl_compiler.py, would fix it.

Comment on lines +258 to +259
* sycl::get_native and sycl::make_* retain the OpenCL object, so references
* returned by get_native or clCreate* must be released by the caller.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: get_native<cl_be>(dev) in _CreateKernelBundle_common_ocl_impl retains the cl_device_id too, and nothing releases it. For a root device that does nothing, but each bundle built for an OpenCL sub-device keeps one more reference. A cl_ref_guard<cl_device_id> with clReleaseDevice would close it.

Comment thread CHANGELOG.md Outdated
Comment on lines +18 to +21
* Kernel bundles in `input`, `object` and `executable` states for the kernels compiled into the application: `dpctl.compiler.get_kernel_bundle`, `has_kernel_bundle`, `compile`, `link`, `build` and `join`, the `dpctl.compiler.SyclKernelId` and `dpctl.compiler.SyclDeviceImage` classes, `get_kernel_ids` and `is_compatible`, and new `dpctl.compiler.SyclKernelBundle` queries (`state`, `backend`, `sycl_context`, `get_devices`, `is_empty`, `get_kernel_ids`, `has_kernel`, `get_kernel`, `get_device_images`, `contains_specialization_constants`, `native_specialization_constant`), with the matching `DPCTLKernelBundle_*`, `DPCTLInputKernelBundle_*`, `DPCTLObjectKernelBundle_*` and `DPCTLKernelId_*` C-API functions
* `selector` argument of `dpctl.compiler.get_kernel_bundle`, a callable that chooses the device images to include, with the `DPCTLKernelBundle_CreateFromContextWithSelector`, `DPCTLInputKernelBundle_CreateFromContextWithSelector`, `DPCTLObjectKernelBundle_CreateFromContextWithSelector` and `DPCTLDeviceImage_HasKernel` C-API functions
* `dpctl4pybind11.hpp` type casters for `sycl::kernel_bundle<sycl::bundle_state::input>`, `sycl::kernel_bundle<sycl::bundle_state::object>` and `sycl::kernel_id`, and the `examples/pybind11/use_kernel_bundle` example that sets a SYCL specialization constant on a kernel bundle obtained in Python
* `dpctl.compiler.load_kernel_library` and the `DPCTLKernelId_LoadLibrary` C-API function, which load a shared library with SYCL device code, e.g. compiled for CUDA or HIP devices, and return the ids of its kernels for use with `dpctl.compiler.get_kernel_bundle`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: The new entries (here, line 30 and line 46) have no [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) link, and the blank lines 17 and 29 split the lists.

@vlad-perevezentsev

Copy link
Copy Markdown
Collaborator

I tested this on Lunar Lake (Level Zero and OpenCL GPU, OpenCL CPU) with DPC++ 2026.2.1 and on Windows (Arc B390, a local build of this branch).
dpctl's tests pass on both, and dpnp's test suite passes with this branch, but dpnp built without it warns on import.
The first four comments below should be addressed before merging.

Comments on lines outside the diff:

  • libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp:743-755: With ownership::transfer, make_kernel_bundle creates a UR program that owns ZeModule before it can still throw. If it throws after that point, the UR program releases the module, and this catch destroys it a second time. Is it guaranteed that DPC++ does not take ownership when it throws? The same applies to zeKernelDestroy at line 793. If not, leaking on that rare error is safer than a double free.

Wrap sycl::kernel_bundle in input, object and executable states, kernel_id
and device images, with get_kernel_bundle, compile, link, build and join in
the C API and dpctl.compiler. DPCTLKernel_GetNumArgs no longer terminates
for kernels without a number of arguments.
SyclKernel device-specific queries become methods with an optional device,
and DPCTLKernel_Get* take a nullable device (breaking). get_kernel_bundle
accepts a device image selector, and dpctl4pybind11.hpp casts input and
object bundles and kernel ids, used by the new use_kernel_bundle example.
Load a shared library with SYCL device code, e.g. built for CUDA or HIP,
and return the ids of the kernels it registered, for get_kernel_bundle.
Exposed as dpctl.compiler.load_kernel_library and DPCTLKernelId_LoadLibrary.
The IL memoryview was typed as strided but passed to the C API as a
contiguous pointer and length. Declare it as const unsigned char[::1] so
non-contiguous buffers are rejected.
The destructor called dlclose/FreeLibrary even when the library failed to
open.
DPCTLKernelBundle_GetKernel, DPCTLKernelBundle_HasKernel and
DPCTLKernelBundle_CreateFromOCLSource could let SYCL exceptions escape an
extern "C" function, which terminates the process. Report them through
error_handler and return the function's failure value.
get_native and make_kernel_bundle/make_kernel retain the OpenCL context,
program and kernel, so the references obtained by dpctl were leaked.
Release them with a scoped guard, and release the kernels created by
_HasKernel_ocl_impl.
The module and kernels were created with ownership::keep and never
destroyed. Use ownership::transfer, destroy them if interop fails, and
destroy the kernel created by _HasKernel_ze_impl.
Append the clBuildProgram or zeModuleCreate build log to the error
reported through error_handler.
A Debug build defines _DEBUG, which makes Windows pyconfig.h enable
Py_DEBUG and reference symbols missing from the release python lib.
Split input and object bundles into SyclInputKernelBundle and
SyclObjectKernelBundle so SyclKernelBundle keeps its layout, restore the
SyclKernel properties (deprecated) and DPCTLKernel_Get* signatures with
device queries under new names, put build logs into the exception, refuse
joins get_sycl_kernel can not handle, and stub the new C API for AdaptiveCpp.
@ndgrigorian
ndgrigorian force-pushed the feature/kernel-bundle-api branch from 78a7927 to 90ec03e Compare December 4, 2026 19:07
@coveralls

Copy link
Copy Markdown
Collaborator

Coverage Status

coverage: 76.45% (+1.3%) from 75.182% — feature/kernel-bundle-api into master

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants